<?php

namespace App\Http\Controllers\Api;

use App\Constants\MemberTaskConstant;
use App\Events\DailyTask;
use App\Http\Requests\Api\CommentRequest;
use App\Http\Requests\Api\IdMustRequest;
use App\Models\TopicComment;

class TopicCommentController extends Controller
{
    public function comment(CommentRequest $request)
    {
        $member = auth('api')->user();
        $content = $request->content;

        $data = [
            'member_id' => $member->id,
            'topic_id' => $request->id,
            'content' => $content,
            'status' => boolval(auth('api')->user()->publisher),
        ];

        if (!$data['status']) {
            $data['status'] = isQuickComment($content, $this->getMiniType());
        }

        $comment = TopicComment::create($data);
        event(new DailyTask($this->getMiniType(), $member->id, MemberTaskConstant::SLUG_BY_COMMENT));

        return $this->success('success', $comment);
    }

    public function favor(IdMustRequest $request)
    {
        $comment = TopicComment::find($request->id);
        $user = auth('api')->user();
        if ($user->favoriteTopicComments()->find($request->id) || !$comment) {
            return $this->success('success');
        }

        $user->favoriteTopicComments()->attach($comment);
        $comment->increment('fav_count');
        $comment->member->increment('favs_count');

        return $this->success('success');
    }

    public function disfavor(IdMustRequest $request)
    {
        $comment = TopicComment::find($request->id);
        $user = auth('api')->user();
        if (!$user->favoriteTopicComments()->find($request->id) || !$comment) {
            return $this->success('success');
        }
        $user->favoriteTopicComments()->detach($comment);
        $comment->decrement('fav_count');
        $comment->member->decrement('favs_count');

        return $this->success('success');
    }
}
